﻿
@{
    ViewBag.Title = "剩余寿命分析";
}
<link href="~/Content/LifeAnalysis/index.css" rel="stylesheet" />
<section class="content">
    <!--内容标题-->
    <div class="content-title row">
        <div class="col-md-6">
            <h3 class="title-brand">剩余寿命分析</h3>
        </div>
        <div class="col-md-6">
            <form class="title-form form-inline" action="">
                <div class="form-group">
                    <label class="control-label" for="">时间选择</label> <span class="glyphicon glyphicon-search"></span>
                    @Html.DropDownList("DateSelect", (IEnumerable<SelectListItem>)ViewBag.DateSelectList, new { @class = "form-control" })
                </div>
            </form>
        </div>
    </div>

    <div class="container-fluid">
        <div class="content-component row">
            <!--故障组件信息-->
            <div class="col-md-6">
                <!--布局图-->
                <div class="panel panel-map panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">风机剩余寿命布局图</div>
                    </div>
                    <div class="panel-body">
                        <div id="map-wrap">
                            <div id="map">
                            </div>
                        </div>
                    </div>
                </div>
                <!--部件故障表格-->
                <div class="panel panel-default panel-componentTable">
                    <div class="panel-heading">
                        <div class="panel-title">风机部件剩余寿命表</div>
                    </div>
                    <div class="panel-body">
                        <table id="componentTable" class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>风机名称</th>
                                    <th>部件名称</th>
                                    <th>剩余寿命(年)</th>
                                    <th>剩余寿命百分比</th>
                                    <th>预警级别</th>
                                </tr>
                            </thead>
                            <tbody id="componentTbody"></tbody>
                        </table>
                    </div>

                </div>
            </div>
            <!--故障传感器信息-->
            <div class="col-md-6">
                <h4 class="sensor-title"><strong>部件剩余寿命周期变化</strong></h4>
                <div id="chart-wrap"></div>
            </div>
        </div>
    </div>
</section>

<!--风机布局图信息框-->
<div id="map-tip">
    <p><span id="map-tip-turbine"></span>号风机</p>
    <p id="map-tip-msg"></p>
</div>


@section scripts{
    <script src="~/Scripts/echarts.min.js"></script>
    <script src="~/Scripts/LifeAnalysis/drawCharts.js"></script>

    <!--左侧导航显示-->
    <script>
        $(function () {
            //展开当前左侧栏父节点
            $("#LifeAnalysis").addClass("in");
            $("#LifeAnalysis>li:first>a").addClass("sidebar-active");
        });
    </script>

    <!--页面初始化-->
    <script>
        var _lastLifeData;   //缓存当前时间所有的寿命信息，改变时间重新读取
        var _lastLifeInfo = {};   //优化后的_lastLifeData
        
        var _chartsData;   //图表数据
        var _chartsInfo = {};   //优化后的_chartsData
        var _times=[];   //x时间轴

        var _currentTurbId='10';   //当前风机
        var _currentComponentId='1';   

        var mapLoaded = false;   //布局图载入完成标志
        var dataLoaded = false;   //布局图数据载入完成标志 (布局图和布局图数据分别异步载入)

        $(function () {   //载入图表
            $("#map").load("/Content/images/turbine.svg", function () {
                mapLoaded = true;   //布局图载入完成
                if (dataLoaded) {
                    drawMapColor();
                }
            });

            initialSelects();

            //初始化表格
            showTableLoading();

            getLastData(fillTable, _currentTurbId);
            getChartData(loadCharts, new Date($("#DateSelect").val()), _currentTurbId, _currentComponentId);
        })
    </script>



    <!--获取数据-->
    <script>

        //获取最新数据，用于布局图和表格
        var getLastData = function (callback, turbineId) {
            $.getJSON('@Url.Action("GetLastLifeData","LifeAnalysis")', function (result) {
                _lastLifeData = result;
                dataLoaded = true;   //布局图数据载入完成

                if (_lastLifeData != null) {

                    var curTurbineId = 0;

                    $.each(_lastLifeData, function (key, value) {

                        if (curTurbineId != Number(value["turbine_id"])) {
                            curTurbineId = Number(value["turbine_id"]);
                            _lastLifeInfo[curTurbineId] = { 'Blade1': null, 'Blade2': null, 'Blade3': null, 'ZhuZhou': null, 'TaDing': null, 'TaDi': null };   //创建新对象
                        }

                        switch (value["component_id"]) {
                            case '1':
                                _lastLifeInfo[curTurbineId]['Blade1'] = Number(value["life_left_estimate"]);
                                break;
                            case '2':
                                _lastLifeInfo[curTurbineId]['Blade2'] = Number(value["life_left_estimate"]);
                                break;
                            case '3':
                                _lastLifeInfo[curTurbineId]['Blade3'] = Number(value["life_left_estimate"]);
                                break;
                            case '4':
                                _lastLifeInfo[curTurbineId]['ZhuZhou'] = Number(value["life_left_estimate"]);
                                break;
                            case '5':
                                _lastLifeInfo[curTurbineId]['TaDing'] = Number(value["life_left_estimate"]);
                                break;
                            case '7':
                                _lastLifeInfo[curTurbineId]['TaDi'] = Number(value["life_left_estimate"]);
                                break;

                            default:

                        }
                    })
                }

                if (mapLoaded) {
                    drawMapColor();
                }
                callback(turbineId);
            })
        }

        //获取图表数据，用于柱状图
        var getChartData = function (callback, day,turbineId,componentId) {   //componentId=1/2/3叶片，4主轴，5塔顶，6塔底
            var data = { "day":day.format("yyyy-MM-dd")};   //参数必须为json对象，且与后台参数同名
            $.getJSON('@Url.Action("GetCycleLifeData", "LifeAnalysis")', data, function (result) {
                _chartsData = result;
                _chartsInfo = {};
                _times=[];

                var d = new Date(day);
                d.setMonth(d.getMonth() - 3);
                var day1 = new Date(d);
                d.setMonth(d.getMonth() - 3);
                var day2 = new Date(d);
                d.setMonth(d.getMonth() - 3);
                var day3 = new Date(d);
                d.setMonth(d.getMonth() - 3);
                var day4 = new Date(d);
                _times.push(day4.format("MM/dd") + "~" + day3.format("MM/dd"));
                _times.push(day3.format("MM/dd") + "~" + day2.format("MM/dd"));
                _times.push(day2.format("MM/dd") + "~" + day1.format("MM/dd"));
                _times.push(day1.format("MM/dd") + "~" + day.format("MM/dd"));

                for (var i = 1; i < 29; i++) {
                    if (_chartsInfo[i] == null) {
                        _chartsInfo[i] = {};
                    }
                    for (var j = 1; j < 8; j++) {
                        if (_chartsInfo[i][j]==null) {
                            _chartsInfo[i][j] = [0, 0, 0, 0, 0];
                        }
                    }
                }

                $.each(result, function (key1, value1) {   //{0:{},1:{},2:{},3:{},4:{}}
                    if (value1.length!=0) {
                        $.each(value1, function (key2, value2) {
                            var tId = Number(value2["turbine_id"]);
                            var comId = Number(value2["component_id"]);

                            //if (_chartsInfo[value2["turbine_id"]] == null) {
                            //    _chartsInfo[value2["turbine_id"]] = {};
                            //}
                            //if (_chartsInfo[value2["turbine_id"]][value2["component_id"]] == null) {
                            //    _chartsInfo[value2["turbine_id"]][value2["component_id"]] = [];
                            //}
                            _chartsInfo[tId][comId][key1]=value2["life_left_estimate"];
                        })
                    }
                    
                })

                //填充表格后，开始填充图表
                //var turbineId = $("#componentTbody tr:first-child").find("span.TurbineId").text();
                //var componentId = $("#componentTbody tr:first-child").find("span.ComponentId").text()
               callback(turbineId, componentId);
            })
        }

    </script>

    <!--通用方法-->
    <script>

        function getLifePercent(life) {   //获取剩余寿命百分比
            return life / 25;
        }

        function getWarnningMsg(life) {   //获取报警级别
            var warningMsg;
            var lifePercent = life / 25;
            if (lifePercent > 0.6) {
                warningMsg = '健康';
            }
            else if (lifePercent > 0.4) {
                warningMsg = '一般预警';
            }
            else if (lifePercent > 0.2) {
                warningMsg = '严重预警';
            }
            else if (lifePercent >= 0) {
                warningMsg = '紧急预警';
            }
            else {
                warningMsg = '';
            }
            return warningMsg;
        }

        function getWarningColor(life) {
            var color = "";
            var lifePercent = life / 25;
            if (lifePercent > 0.6) {
                color = '#00EE00';   //green
            }
            else if (lifePercent > 0.4) {
                color = '#00FFFF';   //blue
            }
            else if (lifePercent > 0.2) {
                color = '#FFFF00';   //yellow
            }
            else if (lifePercent >= 0) {
                color = '#FF0000';   //red
            }
            else {
                color = '#FFFFFF';
            }
            return color;
        }
    </script>


    <!--处理布局图图标-->
    <script>
        var turb;   //当前风机
        var normalTransform = 0;   //正常的Transform参数值
        //鼠标覆盖风机，放大
        var turb_mouseover = function (e) {
            //show tip
            var tid = $(e.currentTarget).attr("tId");
            showMapTip(tid, e.clientX + 10, e.clientY + 30);

            //If IE
            if (IsIE()) return;
            //If else
            turb = $("#t" + tid);
            normalTransform = turb.attr("transform");
            var c = normalTransform.match(/\d{1,3},\d{1,3}/).toString().split(',');
            var lgTransform = "translate(" + String(c[0] - 5) + "," + String(c[1] - 5) + ") scale(1.2,1.2)";  //放大后的Transform参数值
            turb.attr("transform", lgTransform);

        }
        //鼠标移出风机，还原
        var turb_mouseout = function (e) {
            //hide tip
            $("#map-tip").hide();

            //if IE
            if (IsIE()) return;
            //if else
            turb.attr("transform", normalTransform);
        }

        var turb_click = function (e) {
            $("#map svg path").css("fill", "#FFF");   //置白
            var tid = $(e.currentTarget).attr("tId");
            _currentTurbId = tid;
            fillTable(tid);

            _currentComponentId = '1';

            $("#map #t" + tid + " path").css("fill", "#00FF00");   //点击显示绿色
            loadCharts(_currentTurbId, '1');
        }

        //显示提示框
        var showMapTip = function (tid, x, y) {
            var msg = "";
            if (_lastLifeInfo != null) {
                var turbineInfo = _lastLifeInfo[tid];
                if (turbineInfo==null) {
                    return;
                }
                var min = 25;;
                $.each(turbineInfo, function (key, value) {
                    if (min > value) {
                        min = value;
                    }
                })

                msg = "剩余寿命：" + min.toFixed(2) + " 年\n";
                //msg = value["ComponentName"] + " : " + value["TotalTime"] + " 分钟\n";

                if (msg != "") {
                    $("#map-tip").css({ "left": x, "top": y });
                    $("#map-tip-turbine").text(tid);
                    $("#map-tip-msg").text(msg);
                    $("#map-tip").show();
                }
            }
        }

        //绘制风机图标颜色
        var drawMapColor = function () {
            //$("#map svg path").css("fill", "#0E0");   //全部置绿

            $.each(_lastLifeInfo, function (key, value) {
                var min = 25;;
                $.each(value, function (key, value2) {
                    if (min > value2) {
                        min = value2;
                    }
                })
                $("#map #t" + key + " path").css("fill", getWarningColor(min));
            })

        }

    </script>

    <!--处理表格-->
    <script>
        var fillTable = function (turbineId) {
            $("#componentTbody").empty();  //清空表格

            //筛选填充数据
            var turbineInfo = _lastLifeInfo[turbineId];
            if (turbineInfo != null) {
                //叶片
                var bladeLife = (turbineInfo['Blade1'] + turbineInfo['Blade2'] + turbineInfo['Blade3']) / 3;
                $("#componentTbody").append("<tr>"
                            + "<td><span class='TurbineId'>" + turbineId + "</span>&nbsp;2-" + turbineId + "</td>"
                            + "<td><span class='ComponentId'>" + 1 + "</span>叶片</td>"
                            + "<td>" + bladeLife.toFixed(2) + "</td>"
                            + "<td>" + (getLifePercent(bladeLife) * 100).toFixed(2) + "%</td>"
                            + "<td>" + getWarnningMsg(bladeLife) + "</td>"
                            + "</tr>");
                //主轴
                $("#componentTbody").append("<tr>"
                            + "<td><span class='TurbineId'>" + turbineId + "</span>&nbsp;2-" + turbineId + "</td>"
                            + "<td><span class='ComponentId'>" + 4 + "</span>主轴</td>"
                            + "<td>" + turbineInfo['ZhuZhou'].toFixed(2) + "</td>"
                            + "<td>" + (getLifePercent(turbineInfo['ZhuZhou']) * 100).toFixed(2) + "%</td>"
                            + "<td>" + getWarnningMsg(turbineInfo['ZhuZhou']) + "</td>"
                            + "</tr>");
                //塔顶
                $("#componentTbody").append("<tr>"
                            + "<td><span class='TurbineId'>" + turbineId + "</span>&nbsp;2-" + turbineId + "</td>"
                            + "<td><span class='ComponentId'>" + 5 + "</span>塔顶</td>"
                            + "<td>" + turbineInfo['TaDing'].toFixed(2) + "</td>"
                            + "<td>" + (getLifePercent(turbineInfo['TaDing']) * 100).toFixed(2) + "%</td>"
                            + "<td>" + getWarnningMsg(turbineInfo['TaDing']) + "</td>"
                            + "</tr>");
                //塔底
                $("#componentTbody").append("<tr>"
                            + "<td><span class='TurbineId'>" + turbineId + "</span>&nbsp;2-" + turbineId + "</td>"
                            + "<td><span class='ComponentId'>" + 7 + "</span>塔底</td>"
                            + "<td>" + turbineInfo['TaDi'].toFixed(2) + "</td>"
                            + "<td>" + (getLifePercent(turbineInfo['TaDi']) * 100).toFixed(2) + "%</td>"
                            + "<td>" + getWarnningMsg(turbineInfo['TaDi']) + "</td>"
                            + "</tr>");

                $("#componentTbody tr").removeClass("success");
                $("#componentTbody tr:first-child").addClass("success");

                bindTrClick();
            }

        }

        var showTableLoading = function () {
            $("#componentTbody").empty();  //清空表格
            $("#componentTbody").append("<tr><td colspan='5'>正在读取数据......</td></tr>");
        }


    </script>

    <!--处理下拉菜单-->
    <script>
        //绑定下拉列表事件
        var initialSelects = function () {
            //日期下拉列表
            $("#DateSelect").change(function () {
                var day = $("#DateSelect").val();
                getChartData(loadCharts, new Date(day), _currentTurbId, _currentComponentId);
            })
        }


        //改变日期后，重新获取表格数据，清空并写入
        var getComponentTableData = function (day) {
            var data = { "day": day };   //参数必须为json对象，且与后台参数同名
            $.getJSON('@Url.Action("GetComponentFaultData", "RealTimeFault")', data, function (result) {
                _componentFaultData = result;

                dataLoaded = true;   //布局图数据载入完成

                if (mapLoaded) {
                    drawMapColor();
                }
                //填充数据
                fillComponentTable(result);
                //绑定表格行点击事件
                bindTrClick();
                //填充表格后，开始填充图表
                var turbineId = $("#componentTbody tr:first-child").find("span.TurbineId").text();
                var componentId = $("#componentTbody tr:first-child").find("span.ComponentId").text()
                loadCharts(turbineId, componentId);
            })
        }

        //绑定表格行点击事件
        function bindTrClick() {
            $("#componentTbody tr").click(function () {
                $("#componentTbody tr").removeClass("success");
                var turbineId = this.children[0].children[0].innerHTML;
                var componentId = this.children[1].children[0].innerHTML;
                _currentComponentId = componentId;
                loadCharts(turbineId, componentId);
                $(this).addClass("success");
            })
        }
    </script>

    <!--处理图表-->
    <script>
        //装载图表
        var loadCharts = function (turbineId, componentId) {
            //清空图表
            $("#chart-wrap").empty();

            //根据部件不同，调用不同的图表渲染方法 (不同的部件，图表个数，文本，高度，数据源皆不同)
            switch (componentId) {
                case '1':  //叶片
                    drawCom1_HTML();
                    drawCom1_Chart(_times,_chartsInfo,turbineId)
                    break;
                case '4':  //主轴
                case '5':  //塔顶
                case '7':  //塔底
                    drawCom2_HTML(componentId);
                    drawCom2_Chart(_times, _chartsInfo, turbineId, componentId)
                    break;
                default:
            }
        }
    </script>
}



